<template>
    <div>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:gateway:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['business:gateway:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['business:gateway:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                >导出
                </el-button>
            </el-col>
<!--            <el-col :span="1.5">-->
<!--                <el-button-->
<!--                    type="primary"-->
<!--                    plain-->
<!--                    icon="el-icon-edit"-->
<!--                    :disabled="multiple"-->
<!--                    size="mini"-->
<!--                    @click="handlePayBeforeBatch"-->
<!--                >批量充值-->
<!--                </el-button>-->
<!--            </el-col>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="gatewayList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="序号" align="center" type="index" :index="calculateIndex"/>
            <!--      <el-table-column label="网关ID" align="center" prop="gatewayId"/>-->
            <el-table-column label="网关名称" align="center" prop="gatewayName"/>
            <el-table-column label="网关编号" align="center" prop="gatewayNumber"/>
            <el-table-column label="剩余流量(M)" align="center" prop="flowBalance"/>
            <el-table-column label="有效期" align="center" prop="expireTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.expireTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="在线状态" align="center" prop="serverOnline">
                <template slot-scope="scope">
                    <!--                    <div v-if="scope.row.gatewayModelName === 'C-DB-01-001' || scope.row.gatewayModelName === 'C-DB-01-002'">-->
                    <!--                        <svg-icon v-if="scope.row.serverOnline === '1'" icon-class="wifi-online"-->
                    <!--                                  style="width: 4em; height: 4em;"/>-->
                    <!--                        <svg-icon v-if="scope.row.serverOnline === '0'" icon-class="wifi-offline"-->
                    <!--                                  style="width: 4em; height: 4em;"/>-->
                    <!--                    </div>-->
                    <div>
                        <svg-icon v-if="scope.row.serverOnline === '1'" icon-class="wifi-online"
                                  style="width: 4em; height: 4em;"
                        />
                        <svg-icon v-if="scope.row.serverOnline === '0'"
                                  icon-class="wifi-offline"
                                  style="width: 4em; height: 4em;"
                        />
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="信号质量" align="center" prop="gatewaySignal"/>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['business:gateway:edit']"
                    >

                        修改
                    </el-button>
                    <!--          <el-button-->
                    <!--            size="mini"-->
                    <!--            type="text"-->
                    <!--            icon="el-icon-delete"-->
                    <!--            @click="handleDelete(scope.row)"-->
                    <!--            v-hasPermi="['system:gateway:remove']"-->
                    <!--          >删除</el-button>-->
                    <!--                    <el-button-->
                    <!--                        size="mini"-->
                    <!--                        type="text"-->
                    <!--                        @click="settingGateway(scope.row)"-->
                    <!--                        v-hasPermi="['business:gateway:setting']"-->
                    <!--                    >-->
                    <!--                        设置-->
                    <!--                    </el-button>-->
                    <el-button
                        v-if="gatewayModelNBList.indexOf(scope.row.gatewayModelName) !== -1"
                        size="mini"
                        type="text"
                        @click="settingGateway(scope.row)"
                        v-hasPermi="['business:gateway:setting']"
                    >
                        设置
                    </el-button>

<!--                    <el-button-->
<!--                        size="mini"-->
<!--                        type="text"-->
<!--                        @click="showPayBefore(scope.row)"-->
<!--                    >充值-->
<!--                    </el-button>-->

                    <el-button
                        v-if="ledModelList.indexOf(scope.row.gatewayModelName) !== -1"
                        size="mini"
                        type="text"
                        @click="ledScreenMessageSetOpen(scope.row)"
                    >
                        LED
                    </el-button>

                    <!--          <el-button-->
                    <!--            size="mini"-->
                    <!--            type="text"-->
                    <!--            @click="testNetty()"-->

                    <!--          >-->
                    <!--            测试。。-->
                    <!--          </el-button>-->

                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改网关对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">

            <el-form ref="form" :model="form" :rules="rules" label-width="60px" size="small">

                <el-form-item label="项目" prop="projectId">
                    <el-select v-model="form.projectId"
                               placeholder="请选择项目"
                               filterable
                               clearable
                    >
                        <el-option
                            v-for="item in projectList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="名称" prop="gatewayName">
                    <el-input v-model="form.gatewayName" placeholder="请输入网关名称"/>
                </el-form-item>

                <el-form-item label="编号" prop="gatewayNumber">
                    <el-input v-model="form.gatewayNumber" placeholder="请输入网关编号"/>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm()">确 定</el-button>
                <el-button size="small" @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


        <!-- 网关相关设置对话框  -->
        <el-dialog title="网关设置"
                   :visible.sync="gatewaySettingOpen"
                   width="500px"
                   @close="closeGatewaySetting"
                   :close-on-click-modal="false"
                   append-to-body
        >

            <GatewaySet :gateway="form" :key="form.gatewayId"/>

        </el-dialog>


        <el-dialog title="充值网关"
                   :visible.sync="payBeforeOpen"
                   width="500px"
                   append-to-body
                   :close-on-click-modal="false"
        >
            <PayBefore :check-agents="checkAgents" :gateway="form" :key="form.gatewayId"
                       @paySuccess="paySuccess"
            />
        </el-dialog>

<!--        批量充值-->
        <PayBeforeBatch ref="payBeforeBatchDig" @payBatchSuccess="getList"></PayBeforeBatch>


        <el-dialog title="LED屏幕消息"
                   :visible.sync="screenMessageSetOpen"
                   width="650px"
                   @close="closeGatewaySetting"
                   append-to-body
                   :close-on-click-modal="false"
        >

            <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                @click="addScreenMessage()"
            >
            </el-button>

            <!--      <el-link :underline="false" type="primary" @click="addScreenMessage()">添加</el-link>-->

            <el-table :data="this.screenMessageList">

                <el-table-column label="关联信息点" align="center" prop="isSensor" width="90">

                    <template slot-scope="scope">
                        <el-select v-model="scope.row.isSensor">
                            <el-option
                                v-for="item in isSensorList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="信息点" align="center" prop="sensorId" width="150">
                    <template slot-scope="scope" v-if="scope.row.isSensor === '1'">
                        <el-select v-model="scope.row.sensorId"
                                   @change="changeSensor"
                        >
                            <el-option
                                v-for="item in sensorList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="信息点别名" align="center" prop="sensorAlias" width="130">
                    <template slot-scope="scope" v-if="scope.row.isSensor === '1'">
                        <el-input v-model="scope.row.sensorAlias"></el-input>
                    </template>
                </el-table-column>

                <el-table-column label="自定义消息" align="center" prop="customMessage" width="130">
                    <template slot-scope="scope" v-if="scope.row.isSensor === '0'">
                        <el-input v-model="scope.row.customMessage"></el-input>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <!--            <el-button-->
                        <!--              size="small"-->
                        <!--              type="danger"-->
                        <!--              icon="el-icon-delete"-->
                        <!--              @click="deleteScreenMessage(scope.row, scope.$index)"-->
                        <!--            >-->
                        <!--            </el-button>-->
                        <el-link :underline="false" type="danger" @click="deleteScreenMessage(scope.row, scope.$index)">
                            删除
                        </el-link>

                    </template>
                </el-table-column>

            </el-table>


            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitScreenMessage">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>


        </el-dialog>

    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addGateway, delGateway, getGateway, listGateway, updateGateway } from '@/api/equipment/gateway'

import { listSensor } from '@/api/equipment/sensor'
import { addScreenMessageBatch, listScreenMessage } from '@/api/business/screenMessage'
import '@/utils/directives.js'

import { sendMessage } from '@/api/netty/nettyMessage'

import { allProject } from '@/api/business/project'
import PayBefore from '../payBefore/index.vue'
import PayBeforeBatch from '../payBeforeBatch/index.vue'
import GatewaySet from '../set/index.vue'

const common = require('@/api/common/common')

export default {
    name: 'Gateway',
    props: {
        checkAgents: {
            type: Boolean,
            default: false
        }
    },
    data() {
        const checkIP = (rule, value, callback) => {
            const pat1 = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
            // const pat2 = /^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/
            const pat2 = /^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*([\?&]\w+=\w*)*$/
            if (value != null && value !== '') {
                if (pat1.test(value) || pat2.test(value)) {
                    callback()
                } else {
                    callback(new Error('请输入合法的ip地址'))
                }
            } else {
                callback(new Error('请输入ip地址'))
            }
        }

        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            gatewayNumbers: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            gatewayList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                gatewayModel: null,
                gatewayNumber: null,
                gatewayName: null,
                gatewayLongitude: null,
                gatewayLatitude: null,
                gatewaySetupAddress: null,
                projectId: null,
                gpsLongitude: null,
                gpsLatitude: null,
                communityNumber: null,
                baseStationNumber: null,
                online: null,
                serverOnline: null,
                gatewayStatus: null,
                belongCloudControl: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                projectId: [
                    { required: true, message: '请选择项目', trigger: 'blur' }
                ],
                gatewayName: [
                    { required: true, message: '请输入网关名称', trigger: 'blur' }
                ],
                gatewayNumber: [
                    { required: true, message: '请输入网关编号', trigger: 'blur' }
                ]
            },
            // 农业网关型号
            gatewayModelNBList: ['C-NB-05-001', 'C-NB-05-002', 'C-NB-05-003', 'C-NB-05-004', 'C-NB-05-006'],
            ledModelList: ['C-NB-05-003'],
            gatewaySettingOpen: false,
            gatewayOffline: '1',
            loopFault: '0',
            sensorFault: '1',
            // 原站号
            oldStationNumber: null,
            // 新站号
            newStationNumber: null,
            faultNumber: null,
            // 当前网关编号，用于设置IP等操作
            currentGatewayNumber: null,

            globalLoading: false,
            messageObj: {},
            // LED屏幕消息列表，最多3个
            screenMessageList: [],
            screenMessageSetOpen: false,
            isSensorList: [
                { value: '0', label: '否' },
                { value: '1', label: '是' }
            ],
            sensorList: [],
            queryParams2: {
                gatewayId: 0,
                projectId: null
            },
            queryParams3: {
                gatewayId: 0
            },
            currentProjectId: null,
            currentGatewayId: null,
            payBeforeOpen: false,
            payBeforeBatchOpen: false,
        }
    },
    components: {
        GatewaySet,
        PayBefore,
        PayBeforeBatch
    },
    created() {
        this.getProjectId()
        this.getList()
        // console.log('pro',this.projectList)
    },
    computed: {
        ...mapGetters([
            'projectId',
            'projectList'
        ])
    },
    methods: {
        /** 批量充值操作 */
        handlePayBeforeBatch() {
            let obj = {
                gatewayNumbers:this.gatewayNumbers
            }
            this.$refs.payBeforeBatchDig.open(obj)
        },
        paySuccess() {
            this.payBeforeOpen = false
            this.getList()
        },
        showPayBefore(row) {
            this.form = row
            this.payBeforeOpen = true
        },

        // testNetty() {
        //   sendMessageTest().then(response => {
        //
        //   })
        // },

        getProjectId() {
            let id
            if (this.projectId == null) {
                id = sessionStorage.getItem('projectId')
            } else {
                id = this.projectId
            }
            if (!id && typeof (id) !== 'undefined' && id !== 0) id = -1
            this.currentProjectId = id
            this.queryParams2.projectId = id
            this.selectSensorList()
        },

        selectSensorList() {
            this.sensorList = []
            listSensor(this.queryParams2).then(response => {
                for (let item of response.rows) {
                    let temp = {}
                    temp['value'] = item.sensorId
                    temp['label'] = item.sensorName
                    this.sensorList.push(temp)
                }
            })
        },

        submitScreenMessage() {
            let obj = {
                'gatewayId': this.currentGatewayId,
                'screenMessageList': this.screenMessageList
            }

            addScreenMessageBatch(obj).then(response => {
                this.$modal.msgSuccess('成功')
            })
            this.cancel()
        },

        changeSensor(newValue) {
        },

        addScreenMessage() {

            let screenMessage = {}
            screenMessage = {
                'isSensor': '0',
                'sensorAlias': '',
                'customMessage': '',
                'sensorId': null,
                'gatewayId': this.currentGatewayId
            }

            if (this.screenMessageList.length === 3) {
                this.$message.warning('最多添加3条消息')
                return
            }

            this.screenMessageList.push(screenMessage)
        },

        closeGatewaySetting() {
        },

        calculateIndex(index) {
            const pageNum = this.queryParams.pageNum
            const pageSize = this.queryParams.pageSize
            return index + 1 + (pageNum - 1) * pageSize
        },

        deleteScreenMessage(row, index) {
            this.screenMessageList.splice(index, 1)
        },

        // 设置解码器站号
        setSite() {
            let commandArray = []
            commandArray.push(this.oldStationNumber)
            // 写命令
            commandArray.push(0x10)
            // 起始地址
            commandArray.push(256 >> 8 & 0xff)
            commandArray.push(256 & 0xff)

            commandArray.push(0)
            commandArray.push(1)
            commandArray.push(2)

            let controlValue = this.newStationNumber

            commandArray.push(controlValue >> 8 & 0xff)
            commandArray.push(controlValue & 0xff)

            let data = common.buildCode(commandArray)
            let obj = common.buildSendObject('10', 2, data, this.currentGatewayNumber, null)
            this.sendMessage(obj)
        },

        settingGateway(row) {
            this.form = row
            this.gatewaySettingOpen = true
            this.currentGatewayNumber = row.gatewayNumber
        },

        ledScreenMessageSetOpen(row) {

            this.screenMessageList = []

            this.currentGatewayId = row.gatewayId

            this.queryParams3.gatewayId = row.gatewayId

            listScreenMessage(this.queryParams3).then(response => {
                // console.log(response.rows)
                for (let item of response.rows) {
                    let screenMessage = {}
                    screenMessage['isSensor'] = item.isSensor
                    screenMessage['sensorAlias'] = item.sensorAlias
                    screenMessage['customMessage'] = item.customMessage
                    screenMessage['sensorId'] = item.sensorId
                    screenMessage['gatewayId'] = item.gatewayId

                    this.screenMessageList.push(screenMessage)
                }

                this.screenMessageSetOpen = true

            }, error => {

                this.screenMessageSetOpen = true

            })

        },

        getList() {

            // console.log('PC')

            this.queryParams.projectId = this.projectId

            this.loading = true

            listGateway(this.queryParams).then(response => {
                this.gatewayList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        // 取消按钮
        cancel() {
            this.open = false
            this.screenMessageSetOpen = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                gatewayId: null,
                gatewayModel: null,
                gatewayNumber: null,
                gatewayName: null,
                gatewayLongitude: null,
                gatewayLatitude: null,
                gatewaySetupAddress: null,
                projectId: this.projectId,
                gpsLongitude: null,
                gpsLatitude: null,
                communityNumber: null,
                baseStationNumber: null,
                online: null,
                serverOnline: null,
                gatewayStatus: null,
                belongCloudControl: null
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.gatewayId)
            this.gatewayNumbers = selection.map(item => item.gatewayNumber)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加网关'

        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()

            const gatewayId = row.gatewayId || this.ids[0]

            getGateway(gatewayId).then(response => {
                this.form = response.data
                this.open = true
                this.title = '修改网关'

            })
        },

        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {

                    if (this.form.gatewayId != null) {
                        updateGateway(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addGateway(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const gatewayIds = row.gatewayId || this.ids
            this.$modal.confirm('是否确认删除网关编号为"' + gatewayIds + '"的数据项？').then(function() {
                return delGateway(gatewayIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/gateway/export', {
                ...this.queryParams
            }, `gateway_${new Date().getTime()}.xlsx`)
        }

    }
}
</script>
